<?php
namespace backend\modules\member\controllers;

use common\helpers\ArrayHelper;
use common\models\sys\Manager;
use Yii;
use common\models\common\SearchModel;
use common\components\Curd;
use common\models\member\Member;
use common\enums\StatusEnum;
use backend\controllers\BaseController;
use backend\modules\member\forms\RechargeForm;
use yii\base\Model;

/**
 * 会员管理
 *
 * Class MemberController
 * @package backend\modules\member\controllers
 * @author jianyan74 <751393839@qq.com>
 */
class MemberController extends BaseController
{
    use Curd;

    /**
     * @var \yii\db\ActiveRecord
     */
    public $modelClass = Member::class;

    /**
     * 首页
     *
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'partialMatchAttributes' => ['realname', 'mobile'], // 模糊查询
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel
            ->search(Yii::$app->request->queryParams);
        $dataProvider->query
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->andWhere(['>=', 'status', StatusEnum::DISABLED]);
        $daili = Manager::find()->select("rf_sys_manager.id,rf_sys_manager.username")->join('LEFT JOIN','rf_common_auth_assignment','rf_sys_manager.id=rf_common_auth_assignment.user_id')->where(["rf_common_auth_assignment.role_id"=>4,"rf_sys_manager.status"=>1])->asArray()->all();
        $daili = ArrayHelper::map($daili,"username","id");
        $id = Yii::$app->user->id;  //当前登录id
        if(!empty(in_array($id,$daili))) {
            $dataProvider->query->andFilterWhere(['daili' => $id]);
        }
        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    /**
     * 编辑/创建
     *
     * @return mixed|string|\yii\web\Response
     * @throws \yii\base\Exception
     * @throws \yii\base\ExitException
     * @throws \yii\base\InvalidConfigException
     */
    public function actionAjaxEdit()
    {
        $id = Yii::$app->request->get('id');
        $model = $this->findModel($id);
        $model->scenario = 'backendCreate';
        $modelInfo = clone $model;

        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            // 验证密码
            if ($modelInfo['password_hash'] != $model->password_hash) {
                // 记录行为日志
                Yii::$app->services->sysActionLog->create('updateMemberPwd', '创建/修改用户密码|账号:' . $model->username, false);
                $model->password_hash = Yii::$app->security->generatePasswordHash($model->password_hash);
            }
            $daili = Manager::find()->select("rf_sys_manager.id,rf_sys_manager.username")->join('LEFT JOIN','rf_common_auth_assignment','rf_sys_manager.id=rf_common_auth_assignment.user_id')->where(["rf_common_auth_assignment.role_id"=>4,"rf_sys_manager.status"=>1])->asArray()->all();
            $daili = ArrayHelper::map($daili,"username","id");
            $id = Yii::$app->user->id;  //当前登录id
            if(!empty(in_array($id,$daili))) {
                $model->daili = $id;
            }
            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }

        return $this->renderAjax($this->action->id, [
            'model' => $model,
        ]);
    }

    /**
     * 积分/余额变更
     *
     * @param $id
     * @return mixed|string
     * @throws \yii\base\ExitException
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     */
    public function actionRecharge($id)
    {
        $rechargeForm = new RechargeForm();
        $member = $this->findModel($id);

        // ajax 校验
        $this->activeFormValidate($rechargeForm);
        if ($rechargeForm->load(Yii::$app->request->post())) {
            if (!$rechargeForm->save($member)) {
                return $this->message($this->analyErr($rechargeForm->getFirstErrors()), $this->redirect(['index']), 'error');
            }

            return $this->message('充值成功', $this->redirect(['index']));
        }

        return $this->renderAjax($this->action->id, [
            'model' => $member,
            'rechargeForm' => $rechargeForm,
        ]);
    }
    
    /**
     * 允许交易
     *
     * @param $id
     * @return mixed
     */
    public function actionAllow($id)
    {
        if (!($model = Member::findOne($id))) {
            return $this->message("找不到数据", $this->redirect(['index']), 'error');
        }

        $model->prohibit = 1;
        if ($model->save()) {
            return $this->message("修改成功", $this->redirect(['index']));
        }

        return $this->message("修改失败", $this->redirect(['index']), 'error');
    }
    
    /**
     * 禁止交易
     *
     * @param $id
     * @return mixed
     */
    public function actionProhibit($id)
    {
        if (!($model = Member::findOne($id))) {
            return $this->message("找不到数据", $this->redirect(['index']), 'error');
        }

        $model->prohibit = 2;
        if ($model->save()) {
            return $this->message("修改成功", $this->redirect(['index']));
        }

        return $this->message("修改失败", $this->redirect(['index']), 'error');
    }
}